﻿using Newtonsoft.Json;

namespace Mafool.Core;

/// <summary>
/// Float类型序列化保留小数位，默认保留2位
/// 示例: JsonConverter(typeof(FloatRetain), 2)
/// </summary>
public class FloatConverter : JsonConverter<float>
{
    private int _place;

    public FloatConverter() : this(2)
    {
    }

    public FloatConverter(int place)
    {
        this._place = place;
    }

    public override float ReadJson(JsonReader reader, Type objectType, float existingValue, bool hasExistingValue,
        JsonSerializer serializer)
    {
        string v = reader.Value.ToString();
        var number = float.Parse(v);
        return number;
    }

    public override void WriteJson(JsonWriter writer, float value, JsonSerializer serializer)
    {
        writer.WriteValue(Math.Round(value, _place));
    }
}

/// <summary>
/// Double类型序列化保留小数位，默认保留2位
/// 示例: JsonConverter(typeof(DoubleRetain), 2)
/// </summary>
public class DoubleConverter : JsonConverter<double>
{
    private int _place;

    public DoubleConverter() : this(2)
    {
    }

    public DoubleConverter(int place)
    {
        this._place = place;
    }

    public override void WriteJson(JsonWriter writer, double value, JsonSerializer serializer)
    {
        var number = Math.Round(value, _place);
        writer.WriteValue(number);
    }

    public override double ReadJson(JsonReader reader, Type objectType, double existingValue, bool hasExistingValue,
        JsonSerializer serializer)
    {
        string v = reader.Value.ToString();
        var number = double.Parse(v);
        return number;
    }
}


//// 测试
//using Newtonsoft.Json;

//namespace Test
//{
//    public class Model
//    {
//        /// <summary>
//        /// Float示例字段
//        /// </summary>
//        [JsonProperty(PropertyName = "float_field")]
//        [JsonConverter(typeof(FloatConverter))]
//        public float FloatField { get; set; }

//        /// <summary>
//        /// Double示例字段
//        /// </summary>
//        [JsonProperty(PropertyName = "double_field")]
//        [JsonConverter(typeof(DoubleConverter), 3)]
//        public double DoubleField { get; set; }

//        public override string ToString()
//        {
//            return JsonConvert.SerializeObject(this);
//        }
//    }


//    class Program
//    {
//        static void Main(string[] args)
//        {
//            var myObject = new Model
//            {
//                FloatField = 2.71828F,
//                DoubleField = 3.1415926
//            };
//            var settings = new JsonSerializerSettings();

//            string json = JsonConvert.SerializeObject(myObject, settings);
//            Console.WriteLine($"Newtonsoft序 列 化：{json}");

//            var obj = JsonConvert.DeserializeObject<Model>(json);
//            Console.WriteLine($"Newtonsoft反序列化：{obj}");
//            Console.ReadLine();
//        }
//    }
//}